package com.hnkywl.sts.service.htgl;

import com.hnkywl.sts.action.organ.GetBgProvide;
import com.hnkywl.sts.dao.htgl.*;
import com.hnkywl.sts.dao.jhgl.BgjhhzmxDao;
import com.hnkywl.sts.dao.organ.*;
import com.hnkywl.sts.dao.sys.GgDao;
import com.hnkywl.sts.entity.htgl.*;
import com.hnkywl.sts.entity.jhgl.Bgjhhzmx;
import com.hnkywl.sts.entity.organ.*;
import com.hnkywl.sts.service.base.SjzdzService;
import com.hnkywl.sts.service.organ.GsjgService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.webservice.bg.request.*;
import com.hnkywl.sts.webservice.bg.response.Provide;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-4-8
 * Time: 下午1:44
 * To change this template use File | Settings | File Templates.
 */
@Service
public class BghtService {

    // 合同dao
    private HtDao htDao;

    // 采购合同dao
    private CghtDao cghtDao;

    //合同扩展表
    private HtkzDao htkzDao;

    //采购合同明细
    private HtmxDao htmxDao;

    // 公司机构service
    private GsjgService gsjgService;

    // 数据字典service
    private SjzdzService sjzdzService;

    private YgService ygService;

    private GetBgProvide getBgProvide;

    // 物资编码dao
    private GgDao ggDao;

    // 企业法人dao
    private QyfrDao qyfrDao;

    // 企业机构
    private QyjgDao qyjgDao;

    // 企业开户行
    private KhhDao khhDao;

    // 内部部门
    private NbbmDao nbbmDao;

    //保供供应商
    private BggysDao bggysDao;

    //保供合同ID管理
    private BgidglDao bgidglDao;

    //保供付款方式
    private BgfkfsDao bgfkfsDao;

    //合同明细计划明细对照表
    private HtjhdzDao htjhdzDao;

    //保供计划汇总明细DAO
    private BgjhhzmxDao bgjhhzmxDao;

    @Autowired
    public void setHtDao(HtDao htDao) {
        this.htDao = htDao;
    }

    @Autowired
    public void setGsjgService(GsjgService gsjgService) {
        this.gsjgService = gsjgService;
    }

    @Autowired
    public void setSjzdzService(SjzdzService sjzdzService) {
        this.sjzdzService = sjzdzService;
    }

    @Autowired
    public void setGetBgProvide(GetBgProvide getBgProvide) {
        this.getBgProvide = getBgProvide;
    }

    @Autowired
    public void setCghtDao(CghtDao cghtDao) {
        this.cghtDao = cghtDao;
    }

    @Autowired
    public void setHtkzDao(HtkzDao htkzDao) {
        this.htkzDao = htkzDao;
    }

    @Autowired
    public void setHtmxDao(HtmxDao htmxDao) {
        this.htmxDao = htmxDao;
    }

    @Autowired
    public void setGgDao(GgDao ggDao) {
        this.ggDao = ggDao;
    }

    @Autowired
    public void setQyfrDao(QyfrDao qyfrDao) {
        this.qyfrDao = qyfrDao;
    }

    @Autowired
    public void setQyjgDao(QyjgDao qyjgDao) {
        this.qyjgDao = qyjgDao;
    }

    @Autowired
    public void setKhhDao(KhhDao khhDao) {
        this.khhDao = khhDao;
    }

    @Autowired
    public void setNbbmDao(NbbmDao nbbmDao) {
        this.nbbmDao = nbbmDao;
    }

    @Autowired
    public void setYgService(YgService ygService) {
        this.ygService = ygService;
    }

    @Autowired
    public void setBggysDao(BggysDao bggysDao) {
        this.bggysDao = bggysDao;
    }

    @Autowired
    public void setBgidglDao(BgidglDao bgidglDao) {
        this.bgidglDao = bgidglDao;
    }

    @Autowired
    public void setBgfkfsDao(BgfkfsDao bgfkfsDao) {
        this.bgfkfsDao = bgfkfsDao;
    }

    @Autowired
    public void setHtjhdzDao(HtjhdzDao htjhdzDao) {
        this.htjhdzDao = htjhdzDao;
    }

    @Autowired
    public void setBgjhhzmxDao(BgjhhzmxDao bgjhhzmxDao) {
        this.bgjhhzmxDao = bgjhhzmxDao;
    }

    /**
     * 接口保存保供合同信息
     *
     * @param contract
     * @return
     */
    @Transactional
    public void interfaceContract(Contract contract) {
        Cght ht = cghtDao.findBght(contract.getContractNo());
        if (ht != null) {
            //更新主信息
            updateBghtInfo(ht,contract);
            //更新明细信息
            htmxDao.updateBghtmx(contract.getListDetail());
            //更新付款方式
            if (null != contract.getPaymentRateList() && contract.getPaymentRateList().size() > 0) {
                updateBghtFkfsInfo(ht, contract.getPaymentRateList());
            }
        } else {
            // 调用接口查询，保供供应商信息
            Provide provide = getBgProvide.getBgProvideDetail(contract.getProviderCode());
            // 获取合作方
            Qyjg hzf = saveOrUpdateCompInfo(provide, contract);
            if (hzf == null)
                throw new RuntimeException("【" + contract.getProviderName() + "】该供应商信息获取失败!");
            // 保存合同主体信息
            Cght bght = saveBghtInfo(contract, hzf);
            // 保存合同明细和计划明细对照，保供合同附件
            if (null != contract.getCompareList() && contract.getCompareList().size() > 0) {
                saveCompareInfo(contract, bght);
            }
            // 保存合同付款比例
            if (null != contract.getPaymentRateList() && contract.getPaymentRateList().size() > 0) {
                savePaymentRate(bght, contract.getPaymentRateList());
            }
        }
    }

    /**
     * 保存合同付款比例
     *
     * @param paymentRateList
     */
    private void savePaymentRate(Cght bght, List<PaymentRate> paymentRateList) {
        for (PaymentRate paymentRate : paymentRateList) {
            Bgfkfs bgfkfs = new Bgfkfs();
            bgfkfs.setBght(bght);
            bgfkfs.setFksj(paymentRate.getMonth());
            bgfkfs.setFkbl(paymentRate.getRate());
            bgfkfsDao.save(bgfkfs);
        }
    }
    /**
     * 更新付款方式信息
     * @param cght
     */
    private void updateBghtFkfsInfo(Cght cght, List<PaymentRate> paymentRateList){
        List<Bgfkfs> bgfkfsList = new ArrayList<Bgfkfs>();
        for (PaymentRate paymentRate : paymentRateList) {
            Bgfkfs bgfkfs = new Bgfkfs();
            bgfkfs.setFksj(paymentRate.getMonth());
            bgfkfs.setFkbl(paymentRate.getRate());
            bgfkfsList.add(bgfkfs);
        }
        cghtDao.save(cght);
    }

    /**
     * 保存合同明细和计划明细对照
     *
     * @param contract
     * @param bght
     */
    private void saveCompareInfo(Contract contract, Cght bght) {
        List<Compare> compareList = contract.getCompareList();
        Map<Long, Long> temp = new HashMap<Long, Long>();
        //获取供应链物流系统和物资系统合同明细ID的对照
        for (Htmx mx : bght.getHtmxList()) {
            temp.put(mx.getContractDetailId(), mx.getId());
        }
        for (Compare compare : compareList) {
            Htjhdz htjhdz = new Htjhdz();
            htjhdz.setDetailId(compare.getDetailId());
            htjhdz.setBghtmxid(temp.get(compare.getContractDetailId()));
            htjhdzDao.save(htjhdz);
            Bgjhhzmx bgjhhzmx = bgjhhzmxDao.get(compare.getDetailId());
            if (bgjhhzmx != null)
                bgjhhzmx.setZt(7);
        }
    }

    /**
     * 保存保供合同主体信息
     *
     * @param contract
     * @return
     */
    private Cght saveBghtInfo(Contract contract, Qyjg hzf) {
        Cght cght = new Cght();
        cght.setHtbm(contract.getContractNo());
        cght.setCglx("bght");
        cght.setHzf(hzf);
        Nbbm createDepartment = nbbmDao.get(contract.getDepartmentId());
        // 保存申报部门和公司
        if (null != createDepartment) {
            //创建部门
            cght.setCreateDepartment(createDepartment);
            //创建公司
            cght.setCreateOrgan(createDepartment.getSjjg());
            //申报部门
            cght.setSbbm(createDepartment);
            Nbgs nbgs = new Nbgs();
            nbgs.setId(ygService.getZggs(createDepartment).getId());
            //申报公司
            cght.setSbgs(nbgs);
            //物流方部门
            cght.setWlfbm(createDepartment);
            //物流方公司
            cght.setWlfgs(nbgs);
        }
        cght.setQdrq(contract.getContractDate());
        if("2".equals(contract.getType())) {
            cght.setJsrq(contract.getEndDate());
        } else {
            cght.setJsrq(null);
        }
        cght.setDrsj(new Date());
        cght.setHtqdr(contract.getContractPeople());
        cght.setSl(contract.getTaxRate() * 100);
        // 查询合同方式：比价还是招标
        try {
            cght.setZbbj(Long.valueOf(contract.getType()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (null != contract.getDesc()) {
            cght.setBz(contract.getDesc());
        }
        if (contract.getEffect().equals("1")) {
            cght.setZt("ysp");
        } else {
            cght.setZt("ybc");
        }
        cght.setSfdrbght(true);
        // 赋值合同明细信息
        cght.setHtmxList(getBghtDetails(contract, createDepartment));
        // 保存合同信息
        cghtDao.save(cght);

        // 保存保供合同扩展信息 (包含审批信息，审批人，审批时间)
        Htkz htkz = new Htkz();
        htkz.setHt(cght);
        htkzDao.save(htkz);

        // 保存合同id和保供合同id对应关系
        Bgidgl bgidgl = new Bgidgl();
        bgidgl.setHtid(cght.getId());
        bgidgl.setBghtid(contract.getContractId());
        bgidglDao.save(bgidgl);
        return cght;
    }

    /**
     * 更新主信息
     * @param cght
     */
    private void updateBghtInfo(Cght cght,Contract contract){
        cght.setLastUpdated(new Date());
        cghtDao.save(cght);
    }

    /**
     * 保存或者更新企业机构信息
     *
     * @param provide
     */
    private Qyjg saveOrUpdateCompInfo(Provide provide, Contract contract) {
        // 根据保供供应商编码查询，钢贸系统中是否已经存在
        Qyjg qyjg = gsjgService.findGsjgByProvideCode(contract.getProviderCode(), contract.getProviderName());
        //从供应商接口没有获取数据，直接返回本系统企业机构
        if (provide == null)
            return qyjg;
        //当本系统企业机构不为空的时候，判断供应商接口获取的企业机构的最后更新时间是否大于
        // 本系统企业机构最后更新时间，则更新本系统的企业法人信息
        if (qyjg != null) {
            //企业法人
            Qyfr qyfr;
            if (provide.getQyfr() != null && qyjg.getQyfr() != null) {
                //更新企业法人
                qyfr = saveOrUpdateQyfr(provide.getQyfr(), qyjg);
            } else {
                //保存企业法人
                qyfr = saveOrUpdateQyfr(provide.getQyfr(), null);
            }
            // 更新企业机构基础信息
            if (provide.getQyjg() != null) {
                provide.getQyjg().setId(qyjg.getId());
                saveOrUpdateQyjg(provide.getQyjg(), qyfr, contract.getProviderName());
            }
            // 更新企业开户行信息
            if (provide.getKhh() != null) {
                saveOrUpdateKhh(provide.getKhh(), qyjg);
            }
            return qyjg;
        } else {
            // 保存企业法人信息
            Qyfr sqyfr = new Qyfr();
            if (provide.getQyfr() != null) {
                sqyfr = saveOrUpdateQyfr(provide.getQyfr(), null);
            }
            // 保存企业机构基础信息
            Qyjg q = new Qyjg();
            if (provide.getQyjg() != null) {
                q = saveOrUpdateQyjg(provide.getQyjg(), sqyfr, contract.getProviderName());
            }
            // 保存企业开户行信息
            if (provide.getKhh() != null) {
                saveOrUpdateKhh(provide.getKhh(), q);
            }
            Bggys bgygs = new Bggys();
            bgygs.setQyjg(q);
            bgygs.setBggysbm(contract.getProviderCode());
            bggysDao.save(bgygs);
            return q;
        }
    }

    /**
     * 保存开户行信息
     *
     * @param qyjg
     * @return
     */
    private Khh saveOrUpdateKhh(Khh khh, Qyjg qyjg) {
        Khh temp;
        if (null != qyjg.getKhhList() && qyjg.getKhhList().size() > 0) {
            temp = this.khhDao.get(qyjg.getKhhList().get(0).getId());
        } else {
            temp = new Khh();
        }
        if (StringUtils.isNotEmpty(khh.getJc()))
            temp.setJc(khh.getJc());
        if (StringUtils.isNotEmpty(khh.getQc()))
            temp.setQyjg(khh.getQyjg());
        if (StringUtils.isNotEmpty(khh.getZh()))
            temp.setZh(khh.getZh());
        temp.setLastUpdated(new Date());
        temp.setQyjg(qyjg);
        khhDao.save(temp);
        return temp;
    }

    /**
     * 保存或者更新企业机构
     *
     * @param qyjg
     * @param qyfr
     * @param providerName
     * @return
     */
    private Qyjg saveOrUpdateQyjg(Qyjg qyjg, Qyfr qyfr, String providerName) {
        Qyjg temp;
        if (null != qyjg.getId()) {
            temp = this.qyjgDao.get(qyjg.getId());
        } else {
            temp = new Qyjg();
            temp.setQc(providerName);
        }
        if (StringUtils.isNotEmpty(qyjg.getJc()))
            temp.setJc(qyjg.getJc());
        if (StringUtils.isNotEmpty(qyjg.getLxr()))
            temp.setLxr(qyjg.getLxr());
        if (StringUtils.isNotEmpty(qyjg.getLxdh()))
            temp.setLxdh(qyjg.getLxdh());
        if (StringUtils.isNotEmpty(qyjg.getBz()))
            temp.setBz(qyjg.getBz());
        temp.setSfbggys("1");
        temp.setLastUpdated(new Date());
        if (null != qyfr)
            temp.setQyfr(qyfr);
        this.qyjgDao.save(temp);
        return temp;
    }

    /**
     * 保存或者更新企业法人
     *
     * @param pqyfr
     * @param qyjg
     * @return
     */
    private Qyfr saveOrUpdateQyfr(Qyfr pqyfr, Qyjg qyjg) {
        Qyfr temp = new Qyfr();
        if (null != qyjg)
            temp = this.qyfrDao.get(qyjg.getQyfr().getId());
        if (StringUtils.isNotEmpty(pqyfr.getQyqc()))
            temp.setQyqc(pqyfr.getQyqc());
        if (StringUtils.isNotEmpty(pqyfr.getQyjc()))
            temp.setQyjc(pqyfr.getQyjc());
        if (StringUtils.isNotEmpty(pqyfr.getKhh()))
            temp.setKhh(pqyfr.getKhh());
        if (StringUtils.isNotEmpty(pqyfr.getZh()))
            temp.setZh(pqyfr.getZh());
        if (StringUtils.isNotEmpty(pqyfr.getFddlr()))
            temp.setFddlr(pqyfr.getFddlr());
        if (StringUtils.isNotEmpty(pqyfr.getNsh()))
            temp.setNsh(pqyfr.getNsh());
        if (StringUtils.isNotEmpty(pqyfr.getWtdlr()))
            temp.setWtdlr(pqyfr.getWtdlr());
        if (StringUtils.isNotEmpty(pqyfr.getDh()))
            temp.setDh(pqyfr.getDh());
        if (StringUtils.isNotEmpty(pqyfr.getBgdz()))
            temp.setBgdz(pqyfr.getBgdz());
        if (StringUtils.isNotEmpty(pqyfr.getCz()))
            temp.setCz(pqyfr.getCz());
        if (StringUtils.isNotEmpty(pqyfr.getYzbm()))
            temp.setYzbm(pqyfr.getYzbm());
        if (StringUtils.isNotEmpty(pqyfr.getNskhh()))
            temp.setNskhh(pqyfr.getNskhh());
        temp.setLastUpdated(new Date());
        qyfrDao.save(temp);
        return temp;
    }

    /**
     * 保存保供合同明细
     *
     * @param contract        合同信息
     * @param createDepatment 创建部门
     */
    private List<Htmx> getBghtDetails(Contract contract, Nbbm createDepatment) {
        List<ContractDetail> cdList = contract.getListDetail();
        List<Htmx> htmxList = new ArrayList<Htmx>();
        Htmx htmx;
        for (int i = 0; i < cdList.size(); i++) {
            htmx = new Htmx();
            // 根据规格编码，查询规格id
            String ggSql = "select tg.id from t_sys_gg tg, t_sys_bmb tb where tg.code = tb.bmz and tb.bmlxid = 4 and tb.zt = 1  and tb.bmylz2 = ?";
            List list = this.ggDao.findBySQL(ggSql, cdList.get(i).getCode());
            if (null != list && list.size() > 0) {
                BigDecimal ggId = (BigDecimal) list.get(0);
                htmx.setWzgg(this.ggDao.get(ggId.longValue()));
                //如果是招标合同，则更新符合条件的计划明细的状态
                if ("2".equals(contract.getType()))
                    bgjhhzmxDao.cgfsUpdate(ggId.longValue());
            }
            htmx.setContractDetailId(cdList.get(i).getContractDetailId());
            htmx.setCreateDepartment(createDepatment);
            htmx.setCreateOrgan(createDepatment.getSjjg());
            htmx.setSbsl(Double.parseDouble(cdList.get(i).getQty().toString()));
            htmx.setBhsj(Double.parseDouble(cdList.get(i).getPrice().toString()));
            htmx.setHsj(Double.parseDouble(cdList.get(i).getTaxPrice().toString()));
            htmx.setHsje(cdList.get(i).getQty()*cdList.get(i).getTaxPrice());
            htmx.setZt(cdList.get(i).getZt());
            if (StringUtils.isNotEmpty(cdList.get(i).getBrand())) {
                htmx.setPh(cdList.get(i).getBrand());
            }
            if (StringUtils.isNotEmpty(cdList.get(i).getDeliveryDate())) {
                htmx.setJthsjsl(cdList.get(i).getDeliveryDate());
            }
            if (StringUtils.isNotEmpty(cdList.get(i).getDesc())) {
                htmx.setBz(cdList.get(i).getDesc());
            }
            htmxList.add(htmx);
        }
        return htmxList;
    }


    /**
     * 接口禁用合同或者合同明细
     *
     * @param contractForbidList
     */
    @Transactional
    public String InterfaceContractForbid(List<ContractForbid> contractForbidList) {
        try {
            for (ContractForbid contractForbid : contractForbidList) {
                // 禁用合同明细
                ForbidHtDetail(contractForbid.getContractDetailId(), contractForbid.getStopflag());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return "success";
    }

    // 禁用合同明细
    private void ForbidHtDetail(Long contractDetailId, String stopFlag) {
        String zt = "ybc";
        if (null != stopFlag && stopFlag.equals("1")) {
            zt = "yzz";
        }
        // 更新状态
        String detailUpdate = "update t_biz_htmx tm set tm.zt = ? where  tm.contractdetailid= ? ";
        this.htDao.executeSQL(detailUpdate, zt, contractDetailId);
    }

}


